package fr.sedoo.commons.client.widget.table;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;

import fr.sedoo.commons.client.message.CommonMessages;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.client.widget.DialogBoxTools;
import fr.sedoo.commons.shared.domain.IsUrl;

public class PreviewCell extends AbstractCell<IsUrl> {
	private static ImageRenderer renderer;

	/**
	 * Construct a new ImageResourceCell.
	 */
	public PreviewCell() {
		super("click", "keydown");
		if (renderer == null) {
			renderer = new ImageRenderer("100px", "snapshot clickable");
		}
	}

	@Override
	public void render(com.google.gwt.cell.client.Cell.Context context, IsUrl value, SafeHtmlBuilder sb) {
		String aux = StringUtil.trimToEmpty(value.getLink());
		if (StringUtil.isNotEmpty(aux)) {
			// sb.append(renderer.render(context, value.getUrl(), sb));
			renderer.render(context, aux, sb);
		}
	}

	@Override
	public void onBrowserEvent(Context context, Element parent, IsUrl value, NativeEvent event, ValueUpdater<IsUrl> valueUpdater) {
		super.onBrowserEvent(context, parent, value, event, valueUpdater);
		if ("click".equals(event.getType())) {
			EventTarget eventTarget = event.getEventTarget();
			if (!Element.is(eventTarget)) {
				return;
			}
			if (parent.getFirstChildElement().isOrHasChild(Element.as(eventTarget))) {
				// Ignore clicks that occur outside of the main element.
				onEnterKeyDown(context, parent, value, event, valueUpdater);
			}
		}
	}

	@Override
	protected void onEnterKeyDown(Context context, Element parent, IsUrl hasUrl, NativeEvent event, ValueUpdater<IsUrl> valueUpdater) {
		if (hasUrl != null) {
			String aux = StringUtil.trimToEmpty(hasUrl.getLink());
			if (StringUtil.isNotEmpty(aux)) {
				DialogBoxTools.popUpImage(CommonMessages.INSTANCE.view(), aux);
			}
		}
	}

}
